package com.huizhonglm.diap.widget.xGallery;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bruce.common.utils.DateUtil;
import com.bruce.common.utils.EmptyUtil;
import com.bruce.common.utils.FileUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.core.utils.SdcardUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.widget.xGallery.adapter.XPagerAdapter;
import com.huizhonglm.diap.widget.xGallery.view.XViewPager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2015-02-03 09:25
 */
public class XGalleryView extends PopupWindow implements View.OnTouchListener,
        AdapterView.OnItemLongClickListener, XPagerAdapter.OnClickBitmapListener,OnSaveBitmapListener {
    private Context mContext;
    private XViewPager mGallery;
    private View saveView;
    private XPagerAdapter mAdapter;

    private Animation in;
    private Animation out;
    private boolean showSave = false;
    private Bitmap saveBmp;
    private TextView imageNum;
    private int length ;
    private int change;
    public XGalleryView(Context context) {
        super(context);
        this.mContext = context;
        in = AnimationUtils.loadAnimation(mContext, R.anim.anim_alpha_in);
        out = AnimationUtils.loadAnimation(mContext, R.anim.anim_alpha_out);

        View view = View.inflate(context, R.layout.widget_xgallery_view, null);
        imageNum = (TextView)view.findViewById(R.id.num_image_txt);
        saveView = view.findViewById(R.id.save_image_lay);
        Button saveBtn = (Button) view.findViewById(R.id.save_image_btn);
        mGallery = (XViewPager) view.findViewById(R.id.gallery_vp);
        mGallery.setVerticalFadingEdgeEnabled(false);// 取消竖直渐变边框
        mGallery.setHorizontalFadingEdgeEnabled(false);// 取消水平渐变边框
        mGallery.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
            }
            @Override
            public void onPageSelected(int i) {
                change = i+1;
                imageNum.setText(change+"/"+length);
            }
            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
        view.setFocusableInTouchMode(true);
        saveView.setOnTouchListener(this);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSaveView();
                if (saveBmp != null) {
                    String dcimPath = SdcardUtil.getDCIMPath();
                    FileUtil.createDir(dcimPath);
                    if (EmptyUtil.isEmpty(dcimPath)) {
                        ToastUtil.makeTextShort("手机没有SD卡");
                    } else {
                        saveImage(saveBmp);
                        ToastUtil.makeTextShort("图片保存成功");
                    }
                } else {
                    ToastUtil.makeTextShort("图片保存失败");
                }
            }
        });
        setContentView(view);
        setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
        setBackgroundDrawable(new BitmapDrawable());
        setFocusable(true);
        setAnimationStyle(R.style.x_gallery_anim_style);
        update();
    }

    /**
     * 放大加载本地图片
     *
     * @param parent   锚点view
     * @param imgPaths 图片地址集
     */
    public void preview(View parent, List<String> imgPaths, int defIndex) {
        mAdapter = new XPagerAdapter(mContext, "preview", imgPaths);
        mAdapter.setOnClickBitmapListener(this);
        mGallery.setAdapter(mAdapter);
        length = imgPaths.size();
        if (defIndex >= imgPaths.size()) {
            mGallery.setCurrentItem(imgPaths.size() - 1);
        } else if (defIndex < 0) {
            mGallery.setCurrentItem(0);
        }else{
            mGallery.setCurrentItem(defIndex);
        }
        change = mGallery.getCurrentItem()+1;
        imageNum.setText(change+"/"+length);
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
        }
    }

    /**
     * 放大加载网络图片
     *
     * @param parent  锚点view
     * @param imgUrls 图片地址集
     */
    public void show(View parent, List<String> imgUrls, int defIndex) {
        mAdapter = new XPagerAdapter(mContext, "network", imgUrls);
        mAdapter.setOnSaveBitmapListener(this);
        mAdapter.setOnClickBitmapListener(this);
        mGallery.setAdapter(mAdapter);
        length = imgUrls.size();
        if (defIndex >= imgUrls.size()) {
            mGallery.setCurrentItem(imgUrls.size() - 1);
        } else if (defIndex < 0) {
            mGallery.setCurrentItem(0);
        }else{
            mGallery.setCurrentItem(defIndex);
        }
        change = mGallery.getCurrentItem()+1;
        imageNum.setText(change+"/"+length);
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (showSave) {
            hideSaveView();
        } else {
            showSaveView();
        }
        return true;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        hideSaveView();
        return true;
    }

    private void saveImage(Bitmap bmp) {
        String path = SdcardUtil.getDCIMPath() + DateUtil.formatCurrDate("yyyyMMdd_HHmmss") + ".jpg";
        File img = new File(path);
        if (!img.exists()) {
            try {
                img.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(path);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void showSaveView() {
        showSave = true;
        saveView.startAnimation(in);
        saveView.setVisibility(View.VISIBLE);
    }

    private void hideSaveView() {
        showSave = false;
        saveView.startAnimation(out);
        saveView.setVisibility(View.GONE);
    }


    @Override
    public void onSaveBitmap(Bitmap bmp) {
        saveBmp = bmp;
        showSaveView();
    }

    @Override
    public void onCLickBitmap() {
        if (!showSave){
            dismiss();
        }
    }
}
